﻿using System.Collections.Generic;
using System.Linq;
using TechnicalIndicators.Points;
using Utils;

namespace TechnicalIndicators.DateBased
{
	public class RSIAverage : GeneratorBase<DatedSeriePoint, DatedSeriePoint>
	{
		#region Attributes

		private int _valuesProcessed;
		private int _period;
		private readonly List<decimal> _values;

		#endregion

		#region Public Methods

		public RSIAverage() : base()
		{
			_values = new List<decimal>();
		}

		public RSIAverage(ObservableCollection2<DatedSeriePoint> destination) : base(destination)
		{
			_values = new List<decimal>();
		}

		public void Configure(int samples)
		{
			_period = samples;
		}

		protected override DatedSeriePoint CreatePoint(DatedSeriePoint point)
		{
			DatedSeriePoint newPoint = null;

			_valuesProcessed++;

			if (_valuesProcessed > _period)
			{
				newPoint = new DatedSeriePoint(point.X, (base.LastValue.Y * (_period - 1) + point.Y) / _period);
			}
			else if (_valuesProcessed == _period)
			{
				_values.Add(point.Y);
				newPoint = new DatedSeriePoint(point.X, _values.Sum() / _period);
				_values.Clear(); // The data is not needed anymore
			}
			else
			{
				_values.Add(point.Y);
			}

			return newPoint;
		}

		public override void Clear()
		{
			_values.Clear();
			_valuesProcessed = 0;
			base.Clear();
		}

		#endregion
	}
}
